package com.justyh.ssm.controller;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by yh on 2016/10/20.
 */
@Controller
@RequestMapping("/geoplace")
public class GeoPlaceController {
    @RequestMapping(value = "/showPlace",method = RequestMethod.POST)
    @ResponseBody
    public static void main(String [] args) throws InterruptedException {
        System.out.println(new GeoPlaceController().showPlace());
    }
   public Object showPlace() throws InterruptedException {
       JSONObject result=JSONObject.fromObject(this.getPlaces());
        return result;
   }
    public Map getPlaces() throws InterruptedException {
        Map placeList=new LinkedHashMap();
        List<String> province=new ArrayList();
        province.add("北京市");
        province.add("天津市");
        province.add("上海市");
        province.add("重庆市");
        province.add("河北省");
        province.add("河南省");
        province.add("云南省");
        province.add("辽宁省");
        province.add("黑龙江省");
        province.add("湖南省");
        province.add("安徽省");
        province.add("山东省");
        province.add("新疆维吾尔自治区");
        province.add("江苏省");
        province.add("浙江省");
        province.add("江西省");
        province.add("湖北省");
        province.add("广西壮族自治区");
        province.add("甘肃省");
        province.add("山西省");
        province.add("内蒙古自治区");
        province.add("陕西省");
        province.add("吉林省");
        province.add("福建省");
        province.add("贵州省");
        province.add("广东省");
        province.add("青海省");
        province.add("西藏自治区");
        province.add("四川省");
        province.add("宁夏回族自治区");
        province.add("海南省");
//        province.add("台湾省");
//        province.add("香港特别行政区");
//        province.add("澳门特别行政区");
    for(String place:province){
        String result=sendGet("http://restapi.amap.com/v3/config/district","key=a57948d53912fc8a445802bacbed25dd&keywords="+place+"&subdistrict=2");
        JSONObject jsonObject=JSONObject.fromObject(result);
        JSONArray jsonProvinces=(JSONArray) jsonObject.get("districts");
        for(int i=0;i<jsonProvinces.size();i++){
            JSONObject jsonProvince=jsonProvinces.getJSONObject(i);
            JSONArray jsonCitys=JSONArray.fromObject(jsonProvince.get("districts"));
            Map cityMap=new LinkedHashMap();
            Iterator<Object> it = jsonCitys.iterator();
            while(it.hasNext()){
                JSONObject jsonCity=(JSONObject)it.next();
                String cityName=jsonCity.get("name").toString().replaceAll("市","");
                cityName=cityName.replace("辖区","");
                if(cityName.endsWith("郊县")){
                    if(getCounty(jsonCity).size()!=0){
                        List<String> countyList=(List<String>) cityMap.get(cityName.replace("郊县",""));
                        countyList.addAll(getCounty(jsonCity));
                        cityMap.put(cityName.replace("郊县",""),countyList);
                    }else{
                      continue;
                    }
                }else{
                    if(getCounty(jsonCity).size()==0){
                        List<String> counties=new ArrayList<String>();
                        counties.add(cityName);
                        cityMap.put(cityName,counties);
                    }else{
                        cityMap.put(cityName,getCounty(jsonCity));
                    }

                }

            }
            //处理省的格式
            place=place.replace("省","");
            place=place.replace("市","");
            place=place.replace("自治区","");
            place=place.replace("维吾尔","");
            place=place.replace("回族","");
            place=place.replace("壮族","");
            placeList.put(place,cityMap);
        }
        Thread.sleep(100);
    }

//        for (Object key : placeList.keySet()) {
//           // System.out.println( key+":"+ placeList.get(key));
//            System.out.print( key+":"+ "[");
//            for(Object cityKey: ((Map) placeList.get(key)).keySet()){
//                System.out.print(cityKey+",");
//            }
//            System.out.print("]");
//            System.out.println();
//        }


        return placeList;
    }
    public static List<String> getCounty(JSONObject city){
        List<String> countyList=new ArrayList<String>();
        JSONArray countyArr=(JSONArray)city.get("districts");
        for(int i=0;i<countyArr.size();i++){
            JSONObject jsonCounty=countyArr.getJSONObject(i);
            countyList.add(jsonCounty.get("name").toString());
        }
        return  countyList;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
